package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.bean.actgiftdata;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.subordinateclass.RecruitPackage;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;

import java.util.ArrayList;
import java.util.Map;

public class ActiveModule_招募令礼包 extends PlayerModule {

    //bean ---------------------------------------------------

    public static final int acttype = 501;  // 从 actcontrol 这个表中找

    private DateTime startTime; //礼包冷却时间

    private ArrayList<RecruitPackage> dgifts = new ArrayList<RecruitPackage>();

    public ArrayList<RecruitPackage> getDgifts() {
        return dgifts;
    }

    public void setDgifts(ArrayList<RecruitPackage> dgifts) {
        this.dgifts = dgifts;
    }

    public DateTime getStartTime() {
        return startTime;
    }

    public void setStartTime(DateTime startTime) {
        this.startTime = startTime;
    }
    //fnc -----------------------------------------------------


    public static ActiveModule_招募令礼包 create(String pcode) {

        AreaBean ab = AreaModule.area(pcode);
        activeControl sai = activeControl.get(ab.getAreaId(), acttype);
        if (sai != null) {
            ActiveModule_招募令礼包 am = new ActiveModule_招募令礼包();
            am.setPlayerCode(pcode);
            am.setTimeline(sai.getTimeline());
            am.set();
            return am;
        }

        return null;
    }

    public void update() {
        PlayerBean pb = PlayerBean.get(getPlayerCode());
        ServerBean sb = ServerBean.get(pb.getServerId());
        activeControl sai = activeControl.get(String.valueOf(sb.getAreaId()), String.valueOf(acttype));
        if (sai == null) {
            return;
        }


        // 关闭活动
        if (!sai.running() && running()) {
            setTimeline(sai.getTimeline());
            set();
        }

        // 开启活动
        if (sai.running() && !running()) {
            setTimeline(sai.getTimeline());
            setDgifts(new ArrayList<RecruitPackage>());
            set();
        }

        boolean save = false;
        ArrayList<RecruitPackage> newdgifts = new ArrayList<RecruitPackage>();
        for (RecruitPackage dgift : getDgifts()) {
            DateTime end = dgift.getEnd();

            if (DateTime.now().isAfter(end)) {
                save = true;
                continue;
            }

            DateTime locktime = dgift.getLocktime();
            if (locktime != null) {
                DateTime unlocktime = locktime.plusMinutes(5);
                if (DateTime.now().isAfter(unlocktime)) {
                    dgift.setLock(false);
                    dgift.setLocktime(null);
                }
            }

            newdgifts.add(dgift);
        }

        if (save) {
            setDgifts(newdgifts);
            set();
        }

    }

    /**
     * 创建招募令礼包
     *
     * @param num 剩余招募令数量
     */
    public void createRecruitPackage(long num) {
        if (num >= 10) {
            return;
        }

        if (getDgifts() != null && getDgifts().size() > 0) {
            return;
        }

        Map<String, actgiftdata> actmap = ActDataCenter.getAllData(actgiftdata.class, getPlayerCode());
        for (String key : actmap.keySet()) {
            actgiftdata act = actmap.get(key);
            RecruitPackage dgift = new RecruitPackage();
            dgift.setId(act.getId());
            dgift.setGoodsid(act.getPurchasever());
            DateTime start = DateTime.now();
            DateTime end = start.plusMinutes(act.getTimelimit());

            dgift.setStart(start);
            dgift.setEnd(end);

            ArrayList<Currency> curs = (ArrayList<Currency>) Currency.create(act.getRewardtype(), act.getRewardid(), act.getRewardnum());
            dgift.setCurs(curs);
            dgift.setNextID(act.getNextID());//下一个id
            dgift.setPackageName(act.getName()); //礼包名称
            dgift.setNumlimit(act.getNumlimit());//限购次数
            dgift.setBuyNum(0); //已购买次数；
            if (key.equals("101")){
                dgift.setCanBuy(true); //首个礼包可购买
            }else {
                dgift.setCanBuy(false);
            }

            getDgifts().add(dgift);
        }


        set();

        {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.礼包新开启);
        }
    }

    /**
     * 能否购买礼包
     *
     * @param goodsid
     * @return
     */
    public boolean canBuyGiftPackage(int goodsid) {
        for (RecruitPackage dgift : getDgifts()) {
            if (dgift.getGoodsid() == goodsid) {
                if (!dgift.isLock()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 锁单
     *
     * @param goodsid
     */
    public void lockGiftPackage(int goodsid) {
        for (RecruitPackage dgift : getDgifts()) {
            if (dgift.getGoodsid() == goodsid) {
                dgift.setLock(true);
                dgift.setLocktime(DateTime.now());
                set();
                return;
            }
        }
    }

    /**
     * 解锁
     *
     * @param goodsid
     */
    public void unlockGiftPackage(int goodsid) {
        unlockGiftPackageAndSetBuyTime(goodsid, null);
    }

    /**
     * 解锁单 加 设置购买时间
     *
     * @param goodsid
     * @param buytime
     */
    public void unlockGiftPackageAndSetBuyTime(int goodsid, DateTime buytime) {
        int nextId = -1;
        for (RecruitPackage dgift : getDgifts()) {
            if (dgift.getGoodsid() == goodsid) {
                dgift.setLock(false);
                dgift.setLocktime(null);
                dgift.setHadbuy(true); //已购买状态
                int buyNum = dgift.getBuyNum();
                buyNum++;
                dgift.setBuyNum(buyNum); //修改已购买数量
                nextId = dgift.getNextID();
                set();
            }
            if (dgift.getId() == nextId){
                dgift.setCanBuy(true); //下一个礼包可购买
                set();
            }

        }
    }

    // redis ---------------------------------------------------------

    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);
            check();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 ActiveModule_限时连续礼包
     *
     * @param playerCode
     * @return
     */
    static public ActiveModule_招募令礼包 get(String playerCode) {
        try {
            ActiveModule_招募令礼包 module = getv(key(playerCode));
            if (module == null) {
                module = create(playerCode);
            }

            if (module == null) {
                return null;
            }


            module.update();
            module.check();
            return module;
        } catch (RedisException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看是否有可领取奖励 控制红点
     */
    public void check() {
        if (running() && getDgifts().size() >= 1) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
        } else {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
        }
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_招募令礼包 activeModule_招募令礼包 = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_招募令礼包);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }
}
